
import javax.print.DocFlavor;
import java.io.*;
import java.util.Scanner;

public class IODemo9{
    public static void main(String[] args) {
        //先找文件、再匹配内容

        //输入必要内容
        Scanner scanner=new Scanner(System.in);
        System.out.println("please input the path :");
        String rootPath=scanner.next();

        System.out.println("please input the word :");
        String word=scanner.next();

        //进行检查
        File rootFile =new File(rootPath);
        if(!rootFile.isDirectory()){
            System.out.println("error");
            return;
        }
        //查找文件
        scanDir(rootFile,word);
        //匹配内容
    }
    static void scanDir(File rootFile,String word){
        File[] files=rootFile.listFiles();
        if(files == null){
            return;
        }
        for(File f:files){
            System.out.println("current file:"+f);
            if(f.isFile()){
                searchInfile(f,word);
            } else if (f.isDirectory()) {
                scanDir(f,word);
            }else {

            }
        }
    }
    static void searchInfile(File f,String word){
        try(InputStream inputStream=new FileInputStream(f)){
            StringBuilder stringBuilder=new StringBuilder();
            while(true){
                byte[] buffer =new byte[1024];
                int n=inputStream.read(buffer);
                if(n==-1){
                    break;
                }
                String s= new String(buffer,0,n);
                stringBuilder.append(s);
            }
            if(stringBuilder.indexOf(word)==-1){
                return;
            }
            System.out.println("找到了"+word+"存在于"+f.getAbsolutePath());
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

}